import axios from 'axios'
import { Message, Notification, Loading } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { tansParams, blobValidate } from '@/utils/ruoyi'
import errorCode from '@/utils/errorCode'
import { saveAs } from 'file-saver'

const JSONbig = require('json-bigint')({ 'storeAsString': true })

let downloadLoadingInstance

// create an axios instance
const service = axios.create({
  // baseURL: process.env.NODE_ENV === 'production' ? 'http://localhost:8080/' : 'http://localhost:8080/',
  // baseURL: 'http://111.230.63.162:8080/',
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // baseURL: 'http://localhost:8080/',
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
  transformResponse: [function(data) {
    try {
      return JSONbig.parse(data)
    } catch (err) {
      return data
    }
  }]
})

// 请求的拦截
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应的拦截
// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    console.log(response)
    if (response.status == 401) {
      Message({
        message: '登录失效',
        type: 'error',
        duration: 5 * 1000
      })
      this.$router.push(`/login?redirect=${this.$route.fullPath}`)
      return Promise.reject(new Error(res.message || 'Error'))
    } else if (response.status !== 200) {
      Notification.error({ title: '请求失败' })
      return Promise.reject('error')
    }
    // if the custom code is not 20000, it is judged as an error.
    if (res.code && res.code !== 1) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// 通用下载方法
export function download(url, params, filename, config) {
  downloadLoadingInstance = Loading.service({ text: '正在下载数据，请稍候', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' })
  return service.post(url, params, {
    transformRequest: [(params) => { return tansParams(params) }],
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob',
    ...config
  }).then(async(data) => {
    const isBlob = blobValidate(data)
    if (isBlob) {
      const blob = new Blob([data])
      saveAs(blob, filename)
      this.$message.success('文件下载成功')
    } else {
      const resText = await data.text()
      const rspObj = JSON.parse(resText)
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
      this.$message.error(errMsg)
    }
    downloadLoadingInstance.close()
  }).catch((r) => {
    console.error(r)
    Message.error('下载文件出现错误，请联系管理员！')
    downloadLoadingInstance.close()
  })
}

export default service
